package com.xyy.saas.payment.adpater.alipay;

import com.alibaba.fastjson.JSON;
import com.xyy.saas.payment.adpater.channel.setting.ChannelSettingManager;
import com.xyy.saas.payment.adpater.pingxx.domain.PayDO;
import com.xyy.saas.payment.callback.core.handler.CastRequestHandler;
import com.xyy.saas.payment.common.Constants;
import com.xyy.saas.payment.common.exception.PaymentException;
import com.xyy.saas.payment.cores.enums.ResultCodeEnum;
import com.xyy.saas.payment.dao.model.AlipaySettings;
import com.xyy.saas.payment.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: wuqiongda
 * @Date: 2020/3/2 20:00
 */
@Component
public class CastDirectAliPayRequestHandler implements CastRequestHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(CastAliPayRequestHandler.class);

    @Autowired
    private ChannelSettingManager channelSettingManager;

    @Override
    public String getChannel() {
        return Constants.CHANNEL_DIRECT_NAME_ALIPAY;
    }

    @Override
    public Object castRequestHandler(String method, Map<String, String> request, HttpServletRequest requestMsg) throws Exception {
        Object domain = null;
        switch (method) {
            case Constants.METHOD_PAY_SUCCESS_NAME :
                domain = castToPayDo(requestMsg);
                break;
            default:
                LOGGER.error("CastPingxxRequestHandler#castRequestHandler unrecognized method:{} request:{}", method, JSON.toJSONString(request));
                break;
        }
        return domain;
    }
    private PayDO castToPayDo(HttpServletRequest requestMsg) throws PaymentException {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = requestMsg.getParameterMap();
        requestParams.forEach((key, values) -> {
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(key, valueStr);
        });

        //商户订单号
        String payNo = params.get("out_trade_no");
        //支付宝交易号
        String tradeNo = params.get("trade_no");
        BigDecimal decimal = new BigDecimal(params.get("total_amount"));
        Integer fee = decimal.multiply(new BigDecimal(100)).intValue();
        String appId = params.get("app_id");
        AlipaySettings alipaySettings = channelSettingManager.getAlipaySettingsByAliAppId(appId);
        String status = params.get("trade_status");
        PayDO domain = new PayDO();
        domain.setOrderNo(payNo);
        domain.setChannelChargeNo(tradeNo);
        domain.setChannel(Constants.CHANNEL_DIRECT_NAME + "_" + Constants.CHANNEL_ALI_NAME);
        domain.setAmount(fee);
        if ("TRADE_SUCCESS".equals(status)) {
            domain.setResultCode("SUCCESS");
            domain.setReturnCode("SUCCESS");
            try {
                String tradeTime = params.get("gmt_payment");
                domain.setTimePaid(DateUtil.parase(tradeTime, DateUtil.DATEFORMATSECOND));
            } catch (Exception e) {
                LOGGER.error("CastDirectAliPayRequestHandler#castToPayDo cast time error request:{}", JSON.toJSONString(params));
            }
        }
        domain.setPayMode(alipaySettings.getPayMode());
        domain.setChannelTransactionNo(tradeNo);
        domain.setMchId(appId);
        return domain;
    }

}
